import Watcher from './observer/watcher'
import {patch} from './vdom/patch'

export function lifecycleMixin(Vue) {
  Vue.prototype._update = function(vnode) {
    // console.log(vnode)
    const vm = this
    const preVnode = vm._vnode
    vm._vnode = vnode
    console.log(vm)
    if(!preVnode) {
      vm.$el = patch(vm.$el, vnode)
    }else{
      vm.$el = patch(preVnode, vnode)
    }
  }
}

export function mountComponent(vm, el) {
  const options = vm.$options
  vm.$el = el

  callHook(vm, 'beforeMount')

  // 渲染页面
  let updateComponent = () => {
    // 返回的是 虚拟dom
    let vnode = vm._render()
    // 转换成真是dom
    vm._update(vnode)
  }

  // 渲染 watcher 每个组件都有一个watcher
  new Watcher(vm, updateComponent, ()=>{}, true) // true 表示是一个渲染 watcher

  callHook(vm, 'mounted')
}

export function callHook(vm, hook) {
  const handlers = vm.$options[hook];
  if(handlers) {
    for(let i=0; i< handlers.length; i++) {
      handlers[i].call(vm)
    }
  }
}